package com.example.vertification.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.vertification.entity.PageEntity;
import com.example.vertification.entity.User;
import com.example.vertification.entity.UserWithPageEntity;
import com.example.vertification.service.PageService;
import com.example.vertification.service.RegisterCodeService;
import com.example.vertification.service.UserService;
import com.example.vertification.service.UserWithPageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(value = "文章", tags = "文章")
public class PageController {

    private final UserService userService;
    private final PageService pageService;
    private final UserWithPageService userWithPageService;

    @Value("${pages-img-path}")
    private String pageimagesPath;

    @Autowired
    public PageController(UserService userService,PageService pageService,UserWithPageService userWithPageService) {
        this.userService = userService;
        this.pageService = pageService;
        this.userWithPageService = userWithPageService;
    }


//    @PostMapping("contact")
    @GetMapping("/get_all_pages")
    @ApiOperation(value = "传入页数和返回的数量，否则返回所有文章")
    public ResponseEntity<?> get_all_pages(@RequestParam(required = false) int page,@RequestParam(required = false) int size) throws IOException {

        Pageable pageable = PageRequest.of(page-1, size);
        Page<PageEntity> results = pageService.getPageByPageable(pageable);

        JSONArray ja = new JSONArray();

        results.getContent().forEach(pageEntity -> {
            JSONObject obj = new JSONObject();
            obj.set("title",pageEntity.getTitle());
            obj.set("domain",pageEntity.getDomain());
            obj.set("hot",pageEntity.getHot());
            obj.set("imgs",pageEntity.getImgs());
            obj.set("pageID",pageEntity.getPageId());
            obj.set("timestamp",pageEntity.getTimestamp());
            ja.add(obj);
        });

        return ResponseEntity.ok(ja);
    }



    @GetMapping("/get_my_linked_pages")
    @ApiOperation(value = "获取我感兴趣的文章")
    public ResponseEntity<?> get_my_linked_pages(@RequestParam(required = false) String token) throws IOException {
        if (token == null) {
            return ResponseEntity.ok("请先登入");
        }

        User u = userService.getUserByToken(token);
        if (u == null) {
            return ResponseEntity.ok("请先登入");
        }
        UserWithPageEntity ua = userWithPageService.getEntityByUid(u.getUid());
        if (ua == null || ua.getHobbies() == null || ua.getHobbies().equalsIgnoreCase("")) {
            return ResponseEntity.ok("还没有浏览过文章呢,无法确定你喜欢什么哦~");
        }

        JSONArray mytags = JSONUtil.parseArray(ua.getHobbies());
        HashMap<String, Integer> tagInterestMap = new HashMap<>();
        mytags.forEach(tagObj -> {
            JSONObject tag = (JSONObject) tagObj;
            String tagName = tag.getStr("tag");
            int amount = tag.getInt("amount");
            tagInterestMap.put(tagName, amount);
        });

        // 将HashMap转换为List<Map.Entry<String, Integer>>
        List<Map.Entry<String, Integer>> list = new ArrayList<>(tagInterestMap.entrySet());

        // 使用自定义比较器进行降序排序
        list.sort((o1, o2) -> Integer.compare(o2.getValue(), o1.getValue()));

        List<PageEntity> allPages = pageService.getAllPage();

// 根据用户兴趣标签和感兴趣程度对文章进行排序
        List<PageEntity> sortedPages = allPages.stream()
                .filter(page -> page.getTags() != null && !page.getTags().isEmpty()) // 确保文章有标签
                .sorted((p1, p2) -> {
                    // 解析文章标签，并计算与用户兴趣标签的匹配程度
                    List<String> pageTags1 = JSONUtil.parseArray(p1.getTags()).toList(String.class);
                    List<String> pageTags2 = JSONUtil.parseArray(p2.getTags()).toList(String.class);

                    int score1 = calculateScore(pageTags1, tagInterestMap);
                    int score2 = calculateScore(pageTags2, tagInterestMap);

                    // 降序排序
                    return Integer.compare(score2, score1);
                })
                .collect(Collectors.toList());


        return ResponseEntity.ok(sortedPages); // 返回排序和分页后的页面列表

    }

    // 计算文章与用户兴趣标签的匹配程度
    private int calculateScore(List<String> tags, Map<String, Integer> tagInterestMap) {
        int score = 0;
        for (String tag : tags) {
            if (tagInterestMap.containsKey(tag)) {
                score += tagInterestMap.get(tag); // 累加用户的兴趣程度
            }
        }
        return score;
    }





    @GetMapping("/get_page")
    @ApiOperation(value = "传入文章ID")
    public ResponseEntity<?> get_page(@RequestParam long id,@RequestParam(required = false) String token) throws IOException {

        PageEntity page = pageService.getPage(id);
        JSONObject obj = new JSONObject();
        obj.set("title",page.getTitle());
        obj.set("author",page.getAuthor());
        obj.set("timestamp",page.getTimestamp());
        obj.set("pageID",page.getPageId());
        obj.set("domain",page.getDomain());
        obj.set("hot",page.getHot());


        JSONArray content=null;
        if(page.getContent().equalsIgnoreCase("")){
            content=new JSONArray();
        }else{
            content = JSONUtil.parseArray(page.getContent());
        }
        obj.set("content",content);

        JSONArray replies=null;
        if(page.getReplies().equalsIgnoreCase("")){
            replies=new JSONArray();
        }else{
            replies = JSONUtil.parseArray(page.getReplies());
        }



                for(int d = 0;d<replies.size();d++){
                    JSONObject obj_tem = (JSONObject) replies.get(d);
                    obj_tem.set("has_liked",false);

                    User u = userService.getUserByToken(token);
                    if(token!=null){
                        if(u!=null){
                            JSONArray like_array_users_uid = obj_tem.getJSONArray("like_array_users_uid");
                            like_array_users_uid.forEach((e)->{
                                if(e.toString().equalsIgnoreCase(u.getUid().toString())){
                                    obj_tem.set("has_liked",true);
                                }
                            });
                        }
                    }

                    replies.set(d,obj_tem);
                }



        obj.set("replies",replies);



        obj.set("imgs",page.getImgs());


        JSONArray tags=null;
        if(page.getTags().equalsIgnoreCase("")){
            tags=new JSONArray();
        }else{
            tags = JSONUtil.parseArray(page.getTags());
        }
        obj.set("tags",tags);

        return  ResponseEntity.ok(obj);
    }


    @GetMapping("/send_comment")
    @ApiOperation(value = "传入文章ID,用户的token，评论的内容")
    public ResponseEntity<?> send_comment(@RequestParam long id,@RequestParam(required = false) String token,@RequestParam String content) throws IOException {
        if(token==null){
            return ResponseEntity.ok("请先登入");
        }
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入");
        }
        PageEntity page = pageService.getPage(id);
        JSONArray replies = null;
        if(page.getReplies().equalsIgnoreCase("")){
            replies = new JSONArray();
        }else{
            replies = JSONUtil.parseArray(page.getReplies());
        }

        JSONObject obj = new JSONObject();
        obj.set("replyid",replies.size());
        obj.set("replyuid",u.getUid());
        obj.set("content",content);
        obj.set("timestamp",new Date().getTime());
        obj.set("like",0);
        obj.set("like_array_users_uid",new JSONArray());
        obj.set("replies",new JSONArray());
        replies.add(obj);
        page.setReplies(JSONUtil.toJsonStr(replies));
        pageService.savePageEntity(page);
        return ResponseEntity.ok("发表成功");
    }




    @GetMapping("/toggle_like")
    @ApiOperation(value = "传入文章ID,用户的token，评论的ID号")
    public ResponseEntity<?> toggle_like(@RequestParam long id,@RequestParam(required = false) String token,@RequestParam String replyid) throws IOException {
        if (token == null) {
            return ResponseEntity.ok("请先登入");
        }
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入");
        }
        PageEntity page = pageService.getPage(id);

        JSONArray replies = null;
        if(page.getReplies().equalsIgnoreCase("")){
            replies = new JSONArray();
        }else{
            replies = JSONUtil.parseArray(page.getReplies());
        }

        for(int i  = 0;i<replies.size();i++){
           JSONObject obj = (JSONObject)  replies.get(i);
            if(obj.get("replyid").toString().equalsIgnoreCase(replyid)){
                JSONArray has_like_array = obj.getJSONArray("like_array_users_uid");

                boolean check_like = false;
                int index_position = -1;
                for(int c =0;c<has_like_array.size();c++){
                    if (String.valueOf(has_like_array.get(c)).equalsIgnoreCase(u.getUid().toString())){
                        index_position=c;
                        check_like=true;
                    }
                }

                if(check_like){
                    obj.set("like",obj.getInt("like")-1);
                    has_like_array.remove(index_position);
                    obj.set("like_array_users_uid",has_like_array);
                    replies.set(i,obj);
                    page.setReplies(JSONUtil.toJsonStr(replies));
                    pageService.savePageEntity(page);
                    return ResponseEntity.ok("取消点赞成功!");
                }else{
                    obj.set("like",obj.getInt("like")+1);
                    has_like_array.add(u.getUid());
                    obj.set("like_array_users_uid",has_like_array);
                    replies.set(i,obj);
                    page.setReplies(JSONUtil.toJsonStr(replies));
                    pageService.savePageEntity(page);
                    return ResponseEntity.ok("点赞成功!");
                }

            }
        }

        return ResponseEntity.ok("未知错误!");
    }








    @GetMapping("/send_reply")
    @ApiOperation(value = "传入文章ID,用户的token，评论的ID号，回复的内容")
    public ResponseEntity<?> send_comment(@RequestParam long id,@RequestParam(required = false) String token,@RequestParam String replyid,@RequestParam String content) throws IOException {
        if (token == null) {
            return ResponseEntity.ok("请先登入");
        }
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入");
        }
        PageEntity page = pageService.getPage(id);
        JSONArray replies = null;
        if(page.getReplies().equalsIgnoreCase("")){
            replies = new JSONArray();
        }else{
            replies = JSONUtil.parseArray(page.getReplies());
        }


        for(int i  = 0;i<replies.size();i++){
            boolean add_switch=false;
            JSONObject obj = (JSONObject) replies.get(i);
            if(obj.get("replyid").toString().equalsIgnoreCase(replyid)){
                JSONArray ja = obj.getJSONArray("replies");
                JSONObject new_commend_reply = new JSONObject();
                new_commend_reply.set("replyid",ja.size());
                new_commend_reply.set("replyuid",u.getUid());
                new_commend_reply.set("content",content);
                new_commend_reply.set("timestamo",new Date().getTime());
                ja.add(new_commend_reply);
                obj.set("replies",ja);
                add_switch=true;
            }
            if(add_switch==true){
                replies.set(i,obj);
                break;
            }
        }


        page.setReplies(JSONUtil.toJsonStr(replies));
        pageService.savePageEntity(page);
        return ResponseEntity.ok("发表成功");
    }


    @ApiOperation(value = "发布文章,post形式，发token,JSONArray(content),imagesize,domain,title,tags")
    @PostMapping("/submit_page")
    public ResponseEntity<?> open_page(@RequestParam(value = "token",required = false) String token,
                                       @RequestParam("content") String content,
                                       @RequestParam("domain") String domain,
                                       @RequestParam("title") String title,
                                       @RequestParam("tags") String tags,
                                       @RequestParam("images") MultipartFile[] images) throws IOException {
        if (token == null) {
            return ResponseEntity.ok("请先登入");
        }
        User u = userService.getUserByToken(token);
        int imgsize = images.length;
        if(u==null){
            return ResponseEntity.ok("未登录,无法发布文章");
        }


        PageEntity entity = new PageEntity();
        entity.setAuthor(u.getName());

        String[] result_content = content.split("\\r?\\n");


        JSONArray content_arr = new JSONArray();
        for (String paragraph : result_content) {
            content_arr.add(paragraph);
        }

        entity.setContent(JSONUtil.toJsonStr(content_arr));
        entity.setDomain(domain);
        entity.setReplies("[]");
        entity.setHot(0);
        entity.setImgs(imgsize);
        entity.setTitle(title);
        entity.setTimestamp(new Date().getTime());

        JSONArray tags_arr = new JSONArray();

        if(tags.contains(",")){
            String[] tags_list = tags.split(",");
            for(String temp:tags_list){
                tags_arr.add(temp);
            }
        }else{
            tags_arr.add(domain);
        }

        entity.setTags(JSONUtil.toJsonStr(tags_arr));
        pageService.savePageEntity(entity);

        int i =0;
        for(MultipartFile f: images){
            long maxFileSizeInBytes = 5*1024 * 1024; // 1MB
            if (f.getSize() > maxFileSizeInBytes) {
                return new ResponseEntity<>("文件大小超过限制，请上传小于5MB的图片" ,HttpStatus.OK);
            }
            // 构建保存图片的目录路径
            String filePath = pageimagesPath.replace("file:","") + entity.getPageId() + "/";
            File filee=new File(filePath);
            if(!filee.exists()){
                filee.mkdirs();
            }
            f.transferTo(new File(filePath + i + ".jpg"));
            i++;
        }


        return ResponseEntity.ok("发布成功!");
    }


    @GetMapping("/open_page")
    @ApiOperation(value = "打开文章,新增热度(浏览量),以及用户自身的兴趣权重新增.")
    public ResponseEntity<?> open_page(@RequestParam long id,@RequestParam String token) throws IOException {
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("未登录,无法增加热度");
        }
        PageEntity p = pageService.getPage(id);
        p.setHot(p.getHot()+1);

        UserWithPageEntity uwp = userWithPageService.getEntityByUid(u.getUid());
        if(uwp==null){
            UserWithPageEntity insert_obj = new UserWithPageEntity(u.getUid(),JSONUtil.toJsonStr(new JSONArray()));

            userWithPageService.save(insert_obj);
        }

        JSONArray tags = JSONUtil.parseArray(p.getTags());
        // ['科学','运动']
        // [{tag:"美术",amount:100},{tag:"语文",amount:100}]
        JSONArray already_tags = null;
        if(uwp==null||uwp.getHobbies()==null || uwp.getHobbies().equalsIgnoreCase("")){
            already_tags=new JSONArray();
        }else{
            already_tags = JSONUtil.parseArray(uwp.getHobbies());
        }


        for(int e =0;e<tags.size();e++){
            String now_outer_obj = String.valueOf(tags.get(e));
            boolean add_success=false;
            for(int d = 0;d<already_tags.size();d++){
                JSONObject now_inner_obj = (JSONObject)  already_tags.get(d);
                if(now_inner_obj.getStr("tag").equalsIgnoreCase(now_outer_obj)){
                    now_inner_obj.set("amount",now_inner_obj.getInt("amount")+1);
                    already_tags.set(d,now_inner_obj);
                    add_success=true;
                    break;
                }
            }
            if(add_success==false){
                JSONObject obj = new JSONObject();
                obj.set("tag",now_outer_obj);
                obj.set("amount",1);
                already_tags.add(obj);
            }
        }
        if(already_tags==null){
            already_tags = new JSONArray();
        }
        if(uwp == null){
            uwp = new UserWithPageEntity();
            uwp.setUid(u.getUid());
            uwp.setHobbies("[]");
        }
        uwp.setHobbies(JSONUtil.toJsonStr(already_tags));
        userWithPageService.save(uwp);
        pageService.savePageEntity(p);
     return ResponseEntity.ok("新增热度成功");
    }








    @PostMapping("/get_page_domain")
    @ApiOperation(value = "查看文章domain,post形式，发title,content(String)")
    public ResponseEntity<?> get_page_domain(@RequestBody String body) throws IOException {
        JSONObject obj = JSONUtil.parseObj(body);
        String title = obj.getStr("title");
        String content = obj.getStr("content");
        String URL = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={appid}&client_secret={key}";
        String appid = "bmh53ILsmOws8TyXgpCNt3aL";
        String key = "4GRRMwac7MK30cOIo1CHfC77WnnXGib5";
        String Access_token =  new JSONObject(HttpUtil.get(URL.replace("{key}",key).replace("{appid}",appid))).getStr("access_token");
        String Send_To_Url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/topic?charset=UTF-8&access_token="+Access_token;
        JSONObject jsonBody = new JSONObject();
        jsonBody.set("title",title);
        jsonBody.set("content",content);

        JSONObject result_obj = JSONUtil.parseObj(HttpRequest.post(Send_To_Url)
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(jsonBody))
                .execute()
                .body());
        return ResponseEntity.ok(result_obj);
    }


    @PostMapping("/get_page_tags")
    @ApiOperation(value = "查看文章tags,post形式，发title,content(String)")
    public ResponseEntity<?> get_page_tags(@RequestBody String body) throws IOException {
        JSONObject obj = JSONUtil.parseObj(body);
        String title = obj.getStr("title");
        String content = obj.getStr("content");
        String URL = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={appid}&client_secret={key}";
        String appid = "bmh53ILsmOws8TyXgpCNt3aL";
        String key = "4GRRMwac7MK30cOIo1CHfC77WnnXGib5";
        String Access_token =  new JSONObject(HttpUtil.get(URL.replace("{key}",key).replace("{appid}",appid))).getStr("access_token");
        String Send_To_Url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/keyword?charset=UTF-8&access_token="+Access_token;
        JSONObject jsonBody = new JSONObject();
        jsonBody.set("title",title);
        jsonBody.set("content",content);

        JSONObject result_obj = JSONUtil.parseObj(HttpRequest.post(Send_To_Url)
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(jsonBody))
                .execute()
                .body());
        return ResponseEntity.ok(result_obj);
    }



}
